<template>
    <li>
      <label>
<!--        如下代码也能实现功能，但不建议使用-->
<!--        <input type="checkbox" v-model="todoObj.done"/>-->
        <input type="checkbox" :checked="todoObj.done" @change="handleCheck(todoObj.id)"/>
        <span v-show="!todoObj.isEdit">{{todoObj.content}}</span>
        <input
            type="text"
            v-show="todoObj.isEdit"
            :value="todoObj.content"
            @blur="handleBlur(todoObj,$event)"
            ref="inputTitle"
        >
      </label>
      <button class="btn btn-danger" @click="handleDel(todoObj.id)">删除</button>
      <button v-show="!todoObj.isEdit" class="btn btn-edit" @click="handleEdit(todoObj)">编辑</button>
    </li>
</template>

<script>
  import pubsub from "pubsub-js";
  export default {
    name: 'MyItem',
    props:['todoObj'],
    methods:{
      // 勾选or取消勾选
      handleCheck(id){
        // this.checkTodo(id)
        this.$bus.$emit('checkTodo',id)
      },
      // 删除
      handleDel(id){
        if(confirm('确定删除吗？')){
          // this.deleteTodo(id)
          // this.$bus.$emit('deleteTodo',id)
          pubsub.publish('deleteTodo',id)
        }
      },
      // 编辑
      handleEdit(todoObj){
        // 判断是否已经添加了isEdit属性
        if(todoObj.hasOwnProperty('isEdit')){
          todoObj.isEdit = true
        }else{
          this.$set(todoObj,'isEdit',true)
        }
        // 在下一次DOM更新结束后执行其指定的回调
        this.$nextTick(function() {
          this.$refs.inputTitle.focus()
        })
      },
      handleBlur(todoObj,e){
        todoObj.isEdit = false
        if(!e.target.value.trim()) return alert('输入不能为空！')
        this.$bus.$emit('updateTodo',todoObj.id, e.target.value)
      }
    }
  }

</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover{
  background-color: #ddd;
}

li:hover button{
  display: block;
}
</style>